package org.codeasy.site.devtools.ibatissqlformat.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.codeasy.ceutils.regexp.RegExpUtil;
import org.codeasy.ceutils.set.ArrayUtil;
import org.codeasy.ceutils.string.StringUtil;

/**
 * 负责将Ibatis的SQL和参数进行组装的业务类
 * 
 * @author chongan.wangca 2011-9-6 下午04:52:31
 */
public class IbatisSqlFormatService {

	private static List<String> sqlKeywordsList = new ArrayList<String>() {
		{
			add("SELECT");
			add("UPDATE");
			add("DELETE");
			add("INSERT");
		}
	};

	private static String PARAM_START_FLAG = "[";

	private static String PARAM_END_FLAG = "]";

	public static String dealFormat(String sql, String params) {
		if (StringUtil.isBlank(sql) || StringUtil.isBlank(params)) {
			return null;
		}
		String[] paramsArray = params.split(",");
		for (int i = 0; i < paramsArray.length; i++) {
			String rep = paramsArray[i].trim();
			if (!RegExpUtil.isFloat(rep)) {
				if (!"null".equalsIgnoreCase(rep)) {
					rep = "'" + rep + "'";
				}
			}

			sql = sql.replaceFirst("\\?", rep);
		}
		
		if (!sql.endsWith(";")) {
			sql = sql + ";";
		}
		
		sql = StringUtil.blankMany2One(sql);
		return sql;
	}

	public static List<String> format(String sqlsAndParams) throws Exception {
		if (StringUtil.isBlank(sqlsAndParams)) {
			return null;
		}
		List<String> resultList = new ArrayList<String>();
	    String[] sqlsAndParamsArray = sqlsAndParams.split("\n");
	    sqlsAndParamsArray = ArrayUtil.removeBlank(sqlsAndParamsArray);
	    
	    if (sqlsAndParamsArray.length%2 != 0) throw new Exception("不合法的SQL和参数，或者是SQL行数和参数行数不一致"); 
	    
	    for (int i = 0 ; i < sqlsAndParamsArray.length; ) {
	    	String sql = StringUtil.getStartFlagStr(sqlsAndParamsArray[i], sqlKeywordsList);
	    	String param = StringUtil.getBetweenContent(sqlsAndParamsArray[i+1], PARAM_START_FLAG, PARAM_END_FLAG);
	    	resultList.add(dealFormat(sql, param));
	    	i = i + 2;
	    }
		return resultList;
	}
}
